package cn.zwx.base.utils;


import java.net.*;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * IP工具类
 *
 * @author zhangwenxue
 */
public class IpUtils {


    /**
     * 获取本机IP
     */
    protected static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements(); ) {
                //遍历所有的网卡
                NetworkInterface item = enumeration.nextElement();
                for (InterfaceAddress address : item.getInterfaceAddresses()) {
                    if (item.isLoopback() || !item.isUp()) {
                        // 如果是回环和虚拟网络地址的话继续
                        continue;
                    }
                    if (address.getAddress() instanceof Inet4Address) {
                        Inet4Address inet4Address = (Inet4Address) address.getAddress();
                        //只获取ipv4地址
                        return inet4Address.getHostAddress();
                    }
                }
            }
            return InetAddress.getLocalHost().getHostAddress();
        } catch (SocketException | UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 适用于以下情况
     * 1. 开启了vpn
     * 2. 虚拟网卡
     * 3. dubbo 等rpc 将服务注册到了以上两个ip上了
     * 多网卡获取本机ip地址
     *
     * @return ip地址列表
     */
    public static Set<String> getLocalV4Ips() {
        Set<String> localIpSet = new HashSet<>();
        try {
            Enumeration<NetworkInterface> allInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = allInterfaces.nextElement();
                // 去除回环接口，子接口，未运行的接口
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip instanceof Inet4Address) {
                        localIpSet.add(ip.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return localIpSet;
    }

}
